﻿using System.Linq;
using System.Security.Principal;
using Comdiv.QWeb.Factory;
using Comdiv.QWeb.Utils;

namespace Comdiv.QWeb.Security {
	public class SimpleActionRoleChecker {
		public bool IsAuthorized(QWebServiceRegistry registry, IPrincipal usr, ActionDescriptor action, QWebContext context,
		                         IRoleResolver resolver) {
			var roles = Enumerable.ToList(action.Role.split());
			resolver = resolver ?? registry.RoleResolver;
			if (0 == roles.Count || roles.Contains("DEFAULT")) return true;
			roles.Add(action.Name.Replace(".", "_").ToUpper());
			roles.Add((action.Name.Split('.')[0] + "_ALL").ToUpper());
			usr = usr ?? registry.PrincipalSource.CurrentUser;
			if (resolver.IsInRole(usr, "ADMIN", false, context)) return true;
			foreach (var role in roles) {
				if (resolver.IsInRole(usr, role, false, context)) return true;
			}
			return false;
		}
	}
}